<?php

namespace Biz\model\trade;

use Biz\validate\trade\UserAddress as vUserAddress;
use Medoo\Medoo;

class UserAddress extends \Doraemon\pockets\datebase\BaseDbModel
{
    const _CONFIG_FILE_ = 'db_shop';

    const _CONFIG_SELECT_ = 'db_trade';

    const _DATABASE_ = 'shop_trade';

    const _TABLE_NAME = 'user_address';

    const STATUS_NORMAL = 1;

    const STATUS_DEL = 0;

    protected static $fields = [
        'id',
        'uid',
        'accept_name' => ['trim', 'htmlspecialchars'],
        'province',
        'city',
        'area',
        'address' => ['trim', 'htmlspecialchars'],
        'info_address' => ['trim', 'htmlspecialchars'],
        'can_enter_community',
        'have_elevator',
        'which_floor',
        'zipcode',
        'mobile',
        'is_default',
        'addtime',
        'area_code',
    ];

    public static function getDefaultAddress($uid)
    {
        return self::get("*", ['uid' => $uid, 'is_default' => 1, 'status' => self::STATUS_NORMAL]);
    }

    public static function getById($id)
    {
        return self::get("*", ['id' => $id, 'status' => self::STATUS_NORMAL]);
    }

    public static function isFindAddressByUid($uid)
    {
        return self::has(['uid' => $uid, 'status' => self::STATUS_NORMAL]);
    }

    public static function hasMasterAddressByUid($uid)
    {
        $has = self::has_master(Medoo::raw(' where uid=:uid and status=:status for update', [':uid' => $uid, ':status' => self::STATUS_NORMAL]));
        return $has;
    }

    public static function getNumOfAddressByUid($uid)
    {
        return self::count(['uid' => $uid, 'status' => self::STATUS_NORMAL]);
    }

    public static function insertAddress($data)
    {
        try {
            self::_checkFields($data);
            $data['addtime'] = time();
            $data = self::buidData($data);
            self::insert($data);
            if (self::id()) {
                $data['id'] = self::id();
                return $data;
            } else {
                return false;
            }
        } catch (\Exception $e) {
            throw $e;
        }
    }

    public static function saveDefaultAddress($data)
    {
        if ($data['address_id'] && $data['uid']) {
            self::update(['is_default' => 1], ['id' => $data['address_id']]);
            self::update(['is_default' => 0], ['id[!]' => $data['address_id'], 'uid' => $data['uid']]);
            return true;
        }
        return false;
    }

    public static function checkUserAddressById($id, $uid)
    {
        return self::has(['id' => $id, 'uid' => $uid, 'status' => self::STATUS_NORMAL]);
    }

    public static function getAllAddressByUid($userId)
    {
        return self::select('*', ['uid' => $userId, 'status' => self::STATUS_NORMAL, 'ORDER' => ['addtime' => 'DESC']]);
    }

    public static function deleteAddressById($addressId)
    {
        self::update(['status' => self::STATUS_DEL], ['id' => $addressId]);
        return true;
    }

    public static function saveAddressById($addressId, $data,$check=true)
    {
        if($check){
            self::_checkFields($data, $addressId);
        }
        $data = self::buidData($data);
        try {
            self::update($data, ['id' => $addressId]);
            return self::getById($addressId);
        } catch (\Exception $e) {
            throw $e;
        }
    }

    public static function getUserDefaultProvinceCode($uid)
    {
        $result = self::get('province', ['uid' => $uid, 'is_default' => 1, 'status' => self::STATUS_NORMAL]) ?: '';
        return $result;
    }

    public static function getUserDefaultCityCode($uid)
    {
        $result = self::get('city', ['uid' => $uid, 'is_default' => 1, 'status' => self::STATUS_NORMAL]) ?: '';
        return $result;
    }

    private static function _checkFields($data, $addressId = null)
    {
        $scenes = is_null($addressId) ? 'insert' : 'update';
        if (!vUserAddress::validate($data, $scenes)) {
            $msg = vUserAddress::firstError();
            throw new \Exception($msg, -1);
        }
    }
}